package com.ccg.plat.presentation.ui.feature7.view

import android.content.res.Configuration
import android.os.Bundle
import android.view.View
import android.view.ViewGroup
import android.widget.Button
import android.widget.Toast
import androidx.activity.enableEdgeToEdge
import androidx.appcompat.app.AppCompatActivity
import androidx.core.view.ViewCompat
import androidx.core.view.WindowInsetsCompat
import androidx.lifecycle.lifecycleScope
import com.blankj.utilcode.util.BarUtils
import com.blankj.utilcode.util.ScreenUtils
import com.ccg.plat.R
import com.ccg.plat.data.local.cache.UserInfoCache
import com.ccg.plat.presentation.ui.feature4.model.VideoBean
import com.google.gson.Gson
import com.google.gson.reflect.TypeToken
import com.shuyu.gsyvideoplayer.GSYVideoManager
import com.shuyu.gsyvideoplayer.listener.VideoAllCallBack
import com.shuyu.gsyvideoplayer.utils.OrientationUtils
import com.shuyu.gsyvideoplayer.video.StandardGSYVideoPlayer
import com.tencent.mmkv.MMKV
import kotlinx.coroutines.Job
import kotlinx.coroutines.delay
import kotlinx.coroutines.isActive
import kotlinx.coroutines.launch
import timber.log.Timber

/**
 * @author : C4_雍和
 * 描述 : 视频播放器页面，支持横竖屏切换和全屏播放
 * 主要功能 :
 * - 支持自动横竖屏切换
 * - 视频播放控制
 * - 状态栏和导航栏自适应
 * 维护人员 : C4_雍和
 * date : 2025/8/9 9:00
 */
class VideoPlayerTwoActivity : AppCompatActivity() {

    companion object {
        const val EXTRA_VIDEO_JSON = "json"
        private const val COLLECT_KEY = "collect"
        private const val BUTTON_HIDE_DELAY = 4000L
    }

    private lateinit var videoPlayer: StandardGSYVideoPlayer
    private lateinit var collectButton: Button
    private var orientationUtils: OrientationUtils? = null
    private var currentVideoData: VideoBean? = null
    private var videoPlayerHeight = 0
    private val gson = Gson()
    private val mmkv = MMKV.defaultMMKV()
    private val collectListData = mutableListOf<VideoBean>()
    private var hideButtonJob: Job? = null
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        Timber.e("2222222222")
        setupView()
        initializeVideoPlayer()
        setupVideoData()
        loadCollectData()
        setupVideoCallbacks()
        showCollectButton()
    }

    /**
     * 加载收藏数据
     */
    private fun loadCollectData() {
        try {
            val collectJson = mmkv.decodeString(COLLECT_KEY, "") ?: ""
            collectListData.clear()

            if (collectJson.isNotEmpty()) {
                val listType = object : TypeToken<List<VideoBean>>() {}.type
                val loadedList = gson.fromJson<List<VideoBean>>(collectJson, listType)
                collectListData.addAll(loadedList)
            }

            updateCollectButtonText()
            Timber.e("收藏列表加载完成，共${collectListData.size}个视频")
        } catch (e: Exception) {
            Timber.e("加载收藏数据失败")
        }
    }

    /**
     * 设置视图和系统UI
     */
    private fun setupView() {
        enableEdgeToEdge()
        setContentView(R.layout.activity_video_player_two)
        collectButton = findViewById(R.id.btn_collect)
        // 根据缓存状态设置初始屏幕方向
        if (UserInfoCache.isPagerState()) {
            ScreenUtils.setLandscape(this)
        } else {
            ViewCompat.setOnApplyWindowInsetsListener(findViewById(R.id.container)) { view, insets ->
                val systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars())
                view.setPadding(systemBars.left, systemBars.top, systemBars.right, systemBars.bottom)
                insets
            }
            ScreenUtils.setPortrait(this)
        }
    }

    /**
     * 更新收藏按钮文本
     */
    private fun updateCollectButtonText() {
        currentVideoData?.let { videoData ->
            collectButton.text = if (collectListData.contains(videoData)) {
                "删除收藏"
            } else {
                "收藏"
            }
        }
    }

    /**
     * 处理收藏按钮点击
     */
    private fun handleCollectButtonClick() {
        currentVideoData?.let { videoData ->
            if (collectListData.contains(videoData)) {
                // 取消收藏
                collectListData.remove(videoData)
                collectButton.text = "收藏"
                Toast.makeText(this, "已从收藏夹中删除", Toast.LENGTH_SHORT).show()
                Timber.e("取消收藏: ${videoData.name}")
            } else {
                // 添加收藏
                collectListData.add(videoData)
                collectButton.text = "删除收藏"
                Toast.makeText(this, "已添加到收藏夹", Toast.LENGTH_SHORT).show()
                Timber.e("添加收藏: ${videoData.name}")
            }

            saveCollectData()
        }
    }

    /**
     * 保存收藏数据
     */
    private fun saveCollectData() {
        try {
            val collectJson = if (collectListData.isNotEmpty()) {
                gson.toJson(collectListData)
            } else {
                ""
            }
            mmkv.encode(COLLECT_KEY, collectJson)
            Timber.e("收藏数据已保存")
        } catch (e: Exception) {
            Timber.e("保存收藏数据失败")
        }
    }

    /**
     * 显示收藏按钮并在指定时间后隐藏
     */
    private fun showCollectButton() {
        // 取消之前的隐藏任务
        hideButtonJob?.cancel()

        collectButton.visibility = View.VISIBLE

        // 启动新的隐藏任务
        hideButtonJob = lifecycleScope.launch {
            delay(BUTTON_HIDE_DELAY)
            if (isActive) {
                collectButton.visibility = View.GONE
            }
        }
    }

    /**
     * 初始化视频播放器
     */
    private fun initializeVideoPlayer() {
        videoPlayer = findViewById(R.id.video_player)

        orientationUtils = OrientationUtils(this, videoPlayer)
        videoPlayer.isNeedOrientationUtils = true

        setupVideoControls()
    }

    /**
     * 设置视频控制按钮
     */
    private fun setupVideoControls() {
        // 全屏按钮点击事件
        videoPlayer.fullscreenButton.setOnClickListener {
            toggleOrientation()
        }

        // 返回按钮点击事件
        videoPlayer.backButton.setOnClickListener {
            finish()
        }

        // 收藏按钮点击事件
        collectButton.setOnClickListener {
            handleCollectButtonClick()
        }
    }

    /**
     * 设置视频数据
     */
    private fun setupVideoData() {
        intent.getStringExtra(EXTRA_VIDEO_JSON)?.let { jsonString ->
            try {
                currentVideoData = gson.fromJson(jsonString, VideoBean::class.java)
                currentVideoData?.let { data ->
                    videoPlayer.setUp(data.vUrl, true, data.name)
                    videoPlayer.startPlayLogic()
                }
            } catch (e: Exception) {
                Timber.e("Failed to parse video data")
                finish()
            }
        } ?: run {
            Timber.e("No video data provided")
            finish()
        }
    }

    /**
     * 设置视频播放回调
     */
    private fun setupVideoCallbacks() {
        videoPlayer.setVideoAllCallBack(object : VideoAllCallBack {
            override fun onPrepared(url: String?, vararg objects: Any?) {
                Timber.e("onPrepared")
                calculateVideoHeight()
                updateVideoSize()
            }

            override fun onPlayError(url: String?, vararg objects: Any?) {
                Timber.e("onPlayError")
                Timber.e("Video play error: $url")
            }

            // 其他回调方法使用默认实现
            override fun onStartPrepared(url: String?, vararg objects: Any?) {
                Timber.e("onStartPrepared")
            }

            override fun onClickStartIcon(url: String?, vararg objects: Any?) {
                Timber.e("onClickStartIcon")
            }

            override fun onClickStartError(url: String?, vararg objects: Any?) {
                Timber.e("onClickStartError")
            }

            override fun onClickStop(url: String?, vararg objects: Any?) {
                Timber.e("onClickStop")
            }

            override fun onClickStopFullscreen(url: String?, vararg objects: Any?) {
                Timber.e("onClickStopFullscreen")
            }

            override fun onClickResume(url: String?, vararg objects: Any?) {
                Timber.e("onClickResume")
            }

            override fun onClickResumeFullscreen(url: String?, vararg objects: Any?) {
                Timber.e("onClickResumeFullscreen")
            }

            override fun onClickSeekbar(url: String?, vararg objects: Any?) {
                Timber.e("onClickSeekbar")
            }

            override fun onClickSeekbarFullscreen(url: String?, vararg objects: Any?) {
                Timber.e("onClickSeekbarFullscreen")
            }

            override fun onAutoComplete(url: String?, vararg objects: Any?) {
                Timber.e("onAutoComplete")
            }

            override fun onComplete(url: String?, vararg objects: Any?) {
                Timber.e("onComplete")
            }

            override fun onEnterFullscreen(url: String?, vararg objects: Any?) {
                Timber.e("onEnterFullscreen")
            }

            override fun onQuitFullscreen(url: String?, vararg objects: Any?) {
                Timber.e("onQuitFullscreen")
            }

            override fun onQuitSmallWidget(url: String?, vararg objects: Any?) {
                Timber.e("onQuitSmallWidget")
            }

            override fun onEnterSmallWidget(url: String?, vararg objects: Any?) {
                Timber.e("onEnterSmallWidget")
            }

            override fun onTouchScreenSeekVolume(url: String?, vararg objects: Any?) {
                Timber.e("onTouchScreenSeekVolume")
            }

            override fun onTouchScreenSeekPosition(url: String?, vararg objects: Any?) {
                Timber.e("onTouchScreenSeekPosition")
            }

            override fun onTouchScreenSeekLight(url: String?, vararg objects: Any?) {
                Timber.e("onTouchScreenSeekLight")
            }

            override fun onClickStartThumb(url: String?, vararg objects: Any?) {
                Timber.e("onClickStartThumb")
            }

            override fun onClickBlank(url: String?, vararg objects: Any?) {
                Timber.e("onClickBlank")
                showCollectButton()
            }

            override fun onClickBlankFullscreen(url: String?, vararg objects: Any?) {
                Timber.e("onClickBlankFullscreen")
            }
        })
    }

    /**
     * 计算视频播放器高度
     */
    private fun calculateVideoHeight() {
        val videoWidth = videoPlayer.currentVideoWidth
        val videoHeight = videoPlayer.currentVideoHeight

        if (videoWidth > 0 && videoHeight > 0) {
            val screenWidth = ScreenUtils.getScreenWidth()
            videoPlayerHeight = screenWidth * videoHeight / videoWidth
        }
    }

    /**
     * 切换屏幕方向
     */
    private fun toggleOrientation() {
        when (resources.configuration.orientation) {
            Configuration.ORIENTATION_PORTRAIT -> {
                ScreenUtils.setLandscape(this)
            }

            Configuration.ORIENTATION_LANDSCAPE -> {
                ScreenUtils.setPortrait(this)
            }
        }
    }

    /**
     * 更新视频尺寸
     */
    private fun updateVideoSize() {
        when (resources.configuration.orientation) {
            Configuration.ORIENTATION_PORTRAIT -> {
                setPortraitVideoSize()
            }

            Configuration.ORIENTATION_LANDSCAPE -> {
                setLandscapeVideoSize()
            }
        }
    }

    /**
     * 设置竖屏视频尺寸
     */
    private fun setPortraitVideoSize() {
        val params = videoPlayer.layoutParams
        params.width = ViewGroup.LayoutParams.MATCH_PARENT
        params.height = if (videoPlayerHeight > 0) videoPlayerHeight else ViewGroup.LayoutParams.WRAP_CONTENT
        videoPlayer.layoutParams = params
    }

    /**
     * 设置横屏视频尺寸
     */
    private fun setLandscapeVideoSize() {
        val params = videoPlayer.layoutParams
        params.width = ViewGroup.LayoutParams.MATCH_PARENT
        params.height = ViewGroup.LayoutParams.MATCH_PARENT
        videoPlayer.layoutParams = params
    }

    override fun onConfigurationChanged(newConfig: Configuration) {
        super.onConfigurationChanged(newConfig)

        when (newConfig.orientation) {
            Configuration.ORIENTATION_PORTRAIT -> {
                // 竖屏：显示状态栏和导航栏
                BarUtils.setStatusBarVisibility(this, true)
                BarUtils.setNavBarVisibility(this, true)
                setPortraitVideoSize()
            }

            Configuration.ORIENTATION_LANDSCAPE -> {
                // 横屏：隐藏状态栏和导航栏
                BarUtils.setStatusBarVisibility(this, false)
                BarUtils.setNavBarVisibility(this, false)
                setLandscapeVideoSize()
            }
        }
    }

    override fun onPause() {
        super.onPause()
        videoPlayer.onVideoPause()
    }

    override fun onResume() {
        super.onResume()
        videoPlayer.onVideoResume()
    }

    override fun onDestroy() {
        super.onDestroy()
        // 取消协程任务
        hideButtonJob?.cancel()

        try {
            GSYVideoManager.releaseAllVideos()
            orientationUtils?.releaseListener()
        } catch (e: Exception) {
            Timber.e("Error during cleanup")
        }
    }
}